import Phaser from "phaser";
import { createButton } from "../../button";
import { Monster } from "../../sprites/monster";
import { TowerPanel } from "../../sprites/tower";
import { TowerBase } from "../../sprites/tower/base";
import GameState from '../../state/index'

enum tiledMapRectMapEnemu {
  NONE, // 空地
  ROAD, // 道路
  SMALL, // 小障碍物[占1格]
  LITTLE, // 中障碍物[占2格]
  BIG, // 大障碍物[占4格]
  INVALID, // 无效区域
  TOWER // 塔
}

enum ZOrderEnum {
  START = 10, // 起点标识
  CARROT = 0, // 萝卜
  MONSTER = 20, // 怪物
  WAMING = 30, // 警告提示
  TOWER_PANEL = 50 // 创建塔面板
}

export class GamePlay extends Phaser.Scene {
  map!: Phaser.Tilemaps.Tilemap;
  carrot!: Phaser.GameObjects.Image;

  healthValue = 10;
  healthText!: Phaser.GameObjects.BitmapText
  tiledMapRectArray: Phaser.Geom.Rectangle[][] = []
  tiledMapRectArrayMap: tiledMapRectMapEnemu[][] = []
  roadPointArray: Phaser.Geom.Rectangle[] = []

  monsters!: Phaser.Physics.Arcade.Group
  towerPanel: any = null

  // ui
  topBar!: Phaser.GameObjects.Container;
  bottomBar!: Phaser.GameObjects.Container;

  monsterCount = 0
  groupCount = 0

  constructor() {
    super("GamePlay")
  }
  preload() {
    this.load.atlas('megaset', 'assets/GamePlay/Carrot/Carrot1/hlb1.png', 'assets/GamePlay/Carrot/Carrot1/hlb1.json');
    this.load.atlas('bottle', 'assets/GamePlay/Tower/Bottle.png', 'assets/GamePlay/Tower/myBottle.json');

    this.load.atlas('theme', 'assets/GamePlay/Object/Theme1/Monster/theme_1.png', 'assets/GamePlay/Object/Theme1/Monster/my_theme_1.json')
    this.load.image('theme_bg', `assets/GamePlay/Theme/Theme1/BG0/BG1.png`)
    this.load.image('theme_bg_path', `assets/GamePlay/Theme/Theme1/BG${GameState.current_level}/Path${GameState.current_level}.png`)
    this.load.image('tiles', `assets/GamePlay/Theme/Theme1/BG${GameState.current_level}/${GameState.current_level}.png`);
    this.load.image('start_bt', 'assets/GamePlay/Object/Theme1/Object/start01.png')
    this.load.image('start_carrot_hp_bg', 'assets/GamePlay/carrot_hp_bg.png')
    this.load.image('blood_number', 'assets/Font/num_blood.png')

    this.load.image('warning', 'assets/GamePlay/warning.png')
    this.load.image('select_01', 'assets/GamePlay/select_01.png')
    this.load.image('Bottle01', 'assets/GamePlay/Tower/Bottle/Bottle01.png')
    this.load.image('Bottle3', 'assets/GamePlay/Tower/Bottle/Bottle_3.png')
    this.load.image('Bottle31', 'assets/GamePlay/Tower/Bottle/Bottle31.png')
    this.load.image('PBottle31', 'assets/GamePlay/Tower/Bottle/PBottle31.png')

    // UI
    this.load.image('top_bg', 'assets/GamePlay/UI/top_bg.png')
    this.load.image('waves_bg', 'assets/GamePlay/UI/waves_bg.png')
    this.load.image('group_info', 'assets/GamePlay/UI/CN/group_info.png')
    this.load.image('speed_0', 'assets/GamePlay/UI/speed_0.png')
    this.load.image('pause_0', 'assets/GamePlay/UI/pause_0.png')
    this.load.image('menu', 'assets/GamePlay/UI/menu.png')
    this.load.image('bottom_bg', 'assets/GamePlay/UI/bottom_bg.png')
    this.load.image('adv_mission_bg', 'assets/GamePlay/UI/adv_mission_bg.png')
    this.load.image('bar_blank', 'assets/GamePlay/UI/bar_blank.png')
    
    
    this.load.audio('playing_music', 'assets/Sound/GamePlay/BGMusic01.mp3');

    [
      "bar_bomb_02",
      "bar_blood_02",
      "bar_speed_02",
      "bar_ice_02",
      "bar_slow_02"
    ].forEach(item => {
      this.load.image(item, `assets/GamePlay/UI/${item}.png`)
    })
    for(let i = 1; i <= 10; i++) {
      this.load.image(`end_sign_pic${i}`, `assets/GamePlay/Carrot/Carrot1/hlb1_${i}.png`)
      // this.load.image(`S${i}`, `assets/GamePlay/Object/Theme1/Object/S${i}.png`)
    }
  
    for(let i = 1; i < 4; i++) {
      this.load.image(`S${i}`, `assets/GamePlay/Object/Theme1/Object/S${i}.png`)
    }
    for(let i = 1; i < 4; i++) {
      this.load.image(`L${i}`, `assets/GamePlay/Object/Theme1/Object/L${i}.png`)
    }
    for(let i = 1; i < 3; i++) {
      this.load.image(`B${i}`, `assets/GamePlay/Object/Theme1/Object/B${i}.png`)
    }
    for(let i = 1; i < 4; i++) {
      this.load.image(`Monster_L${i}`, `assets/GamePlay/Object/Theme1/Monster/L1${i}.png`)
    }
  
    this.load.tilemapTiledJSON({
      key: 'map',
      url: 'assets/GamePlay/Theme/Theme1/BG1/Level1.json'
    });
  }
  create() {
    // 播放游戏中的背景音乐
    // this.sound.add('playing_music', { loop: true }).play()

    this.monsters = this.physics.add.group({ allowGravity: false });
    this.createBackgroundLayer()
    this.createMainLayer()
    this.createUI()
  }

  createBackgroundLayer() {
    this.add.image(this.cameras.main.centerX, this.cameras.main.centerY, 'theme_bg')
  }

  createUI() {
    // 顶部菜单栏
    this.loadTopBar();
    // 金币
    this.loadGoldText()
    // 组信息
    this.loadGroupInfo()
    // 顶部按钮
    this.loadTopButtons()
    //底部菜单栏
    this.loadBottomBar();
    // 任务背景
    this.loadMissionBg();
    // 底部按钮
    this.loadBottomButtons();
  }

  loadTopBar() {
    const box = this.add.container(0, 0)
    const bg = this.add.image(this.cameras.main.centerX, 0, 'top_bg').setOrigin(0.5, 0)
    const centerNode = this.add.sprite(this.cameras.main.centerX, 0, 'waves_bg')
    centerNode.x = bg.width / 2 + centerNode.width / 2
    centerNode.y = bg.height / 2

    const groupInfo = this.add.image(10, 10, 'group_info').setOrigin(0.5, 0.5)
    groupInfo.x = centerNode.x 
    groupInfo.y = centerNode.height / 2

    box.add(bg)
    box.add(centerNode)
    box.add(groupInfo)
    this.topBar = box
  }

  loadGoldText() {
    const stoneText = this.add.text(0, 0, '04').setFontSize(32);
    // stoneText.setOrigin(0.5, 0.5)
    stoneText.setPosition(185, 13)
    this.topBar.add(stoneText)
  }

  loadGroupInfo() {
    let node = this.add.text(0, 0, '1').setFontSize(32);
    // stoneText.setOrigin(0.5, 0.5)
    const bg = this.topBar.getAt(0) as any
    node.x = bg.width / 2 + 45
    node.y = bg.height / 2 - 25
    this.topBar.add(node)

    node = this.add.text(0, 0, `${GameState.MAX_GROUP_COUNT}`).setFontSize(32);
    node.x = bg.width / 2 + 105
    node.y = bg.height / 2 - 25
    this.topBar.add(node)
  }

  loadTopButtons() {
    let node = createButton(this, 'speed_0', 'speed_0', () => {})
    node.x = 820
    node.y = this.topBar.getAt(0).height / 2
    this.topBar.add(node)

    node = createButton(this, 'pause_0', 'pause_0', () => {})
    node.x = 920
    node.y = this.topBar.getAt(0).height / 2
    this.topBar.add(node)

    node = createButton(this, 'menu', 'menu', () => {})
    node.x = 990
    node.y = this.topBar.getAt(0).height / 2
    this.topBar.add(node)
  }

  loadBottomBar() {
    this.bottomBar = this.add.container(this.cameras.main.centerX, this.cameras.main.height)
    let node = this.add.image(0, 0, 'bottom_bg').setOrigin(0.5, 1)

    this.bottomBar.add(node)
    
  }

  loadMissionBg() {
    let node = this.add.image(0, 0, 'adv_mission_bg').setOrigin(0, 1)
    node.x = 50 -this.bottomBar.getAt(0).width / 2
    node.y = 20
    this.bottomBar.add(node)
  }

  loadBottomButtons() {
    let nextPosX = 370 - this.bottomBar.getAt(0)?.width / 2;
    const offsetX = 10;
    [
      "bar_bomb_02",
      "bar_blood_02",
      "bar_speed_02",
      "bar_ice_02",
      "bar_slow_02"
    ].forEach((item) => {
      const btn = this.add.container(0, 0)
      const bg = this.add.image(nextPosX, 0, 'bar_blank').setOrigin(0, 1)
      const bt = this.add.image(nextPosX, 0, item).setOrigin(0, 1)
      btn.add(bg)
      btn.add(bt)

      nextPosX += bg.width + offsetX
      this.bottomBar.add(btn)
    })
  }

  createMainLayer() {
    this.loadProperty()
    // 加载路径
    this.loadPath()
    // 加载瓦片
    this.loadTiledMap()
    // 加载开始按钮
    this.loadStartButton()
    // 加载结束按钮
    this.loadEndButton()
    // 血条背景
    this.loadBloodBg()
    // 血条
    this.loadBlood()
    // 可触摸安装控件
    this.loadCanTouchRect()
    this.loadTiledMapRectArrayMap()
    this.loadRoadPointArray()

    // 读取地图中的路障和禁用区域
    this.loadObstacle()

    this.loadRoadMap()

    this.loadNextGroupMonster()

    this.input.on('pointerdown', (pointer: any, gameObjects: any) => {
      // console.log(gameObjects.length > 0 && gameObjects[0].getData('name'))
      if (gameObjects.length > 0 && gameObjects[0].name === 'bottle') {
        return ;
      }
      pointer.event.preventDefault()
      var result = this.getInfoFromMapByPos(pointer.downX, pointer.downY);
      console.log(result)
      // console.log(pointer)
      if (!result.isInMap) {
        this.loadTouchWarning(pointer.downX, pointer.downY);
      } else if (this.tiledMapRectArrayMap[result.row][result.cel] != tiledMapRectMapEnemu.NONE) {
        this.loadTouchWarning(result.x + this.map.tileWidth / 2, result.y + this.map.tileHeight / 2);
      } else {
        if (this.towerPanel == null) {
          this.loadTowerPanel({
              cel : result.cel,
              row : result.row,
              x :result.x,
              y: result.y
          });
        }else{
          this.towerPanel && this.towerPanel.destroyAll()
          // self.removeChild(self.towerPanel);
          this.towerPanel = null;
        }
      }
    })
  }

  loadProperty() {}

  loadPath() {
    this.add.image(this.cameras.main.centerX, this.cameras.main.centerY, 'theme_bg_path')
  }

  loadTiledMap() {
    this.map = this.make.tilemap({ key: 'map' });
    var tiles = this.map.addTilesetImage('1', 'tiles');
    if (!tiles) {
      return
    }
    let tileHeight = tiles.tileHeight
    let tileWidth = tiles.tileWidth
    var layer = this.map.createLayer(0, tiles, 0, 0);
    if (!layer) {
      return
    }

    layer.setPosition(this.cameras.main.centerX - layer.width / 2, this.cameras.main.centerY - layer.height / 2)
    layer.setVisible(false)

    var objs = this.map.objects
    let finalOffsetX = 0;
    let finalOffsetY = 0;
    let offsetX = (this.cameras.main.width - this.map.widthInPixels) / 2;
    let offsetY = (this.map.heightInPixels ) / 2;

    for (let i = 0; i < objs.length; i ++) {
      let layer = objs[i];
      console.log('layer--->>>', layer)
      let groupName = layer.name;
      if (groupName === 'big') {
        finalOffsetX = offsetX;
        finalOffsetY = offsetY;
      } else if (groupName === 'little') {
        finalOffsetX = offsetX;
        finalOffsetY = offsetY + tileHeight / 2;
      } else if (groupName == "small"
      || groupName == "road"
      || groupName == "start_end"
      || groupName == "invalid") {
        finalOffsetX = offsetX + tileWidth / 2;
        finalOffsetY = offsetY + tileHeight / 2;
      } else {
        console.log('something wrong with the map')
      }
      console.log(i, layer, finalOffsetX, finalOffsetY)
      layer.properties = {finalOffsetX, finalOffsetY}
      // layer.y = finalOffsetY
    }
  }

  loadStartButton() {
    var startBt = this.add.sprite(0, 0, 'start_bt')
    var objs = this.map.getObjectLayer('start_end')
    var obj = objs?.objects[0]
    if (objs && obj && obj.x) {
      startBt.setPosition(obj.x + (objs.properties as any).finalOffsetX, obj.y)
    }
  }

  loadEndButton () {
    var endBt = this.add.image(0, 0, 'end_sign_pic10');
    var objs = this.map.getObjectLayer('start_end')
    var obj = objs?.objects[1]
    if (objs && obj && obj.x && obj.y) {
      endBt.setPosition(obj.x + (objs.properties as any).finalOffsetX, obj.y - 15)
    }
    this.carrot = endBt
  }
  
  loadBloodBg() {
    this.add.sprite(this.carrot.x + 75, this.carrot.y + 30, 'start_carrot_hp_bg')
  }

  loadBlood() {
    const config: Phaser.Types.GameObjects.BitmapText.RetroFontConfig = {
      image: 'blood_number',
      width: 16,
      height: 22,
      chars: Phaser.GameObjects.RetroFont.TEXT_SET8,
      charsPerRow: 8,
      'spacing.x': 0,
      'spacing.y': 0,
      'offset.x': 0,
      'offset.y': 0,
      lineSpacing: 0
    };

    this.cache.bitmapFont.add('blood_number', Phaser.GameObjects.RetroFont.Parse(this, config));
    this.healthText  = this.add.bitmapText(this.carrot.x + 44, this.carrot.y + 20, 'blood_number', this.healthValue + '');
  }

  loadCanTouchRect() {
    var mapWidth = this.map.width;
    var mapHeight = this.map.height;
    var winSize = this.cameras.main;
    var nextPosX = (winSize.width - this.map.widthInPixels) / 2 + this.map.tileWidth / 2;
    var nextPosY = (winSize.height - this.map.heightInPixels) / 2 + this.map.tileHeight / 2;

    for (var i = 0; i < mapHeight; i++) {
      this.tiledMapRectArray[i] = [];
      for (var j = 0; j < mapWidth; j++) {
          // 空地
          this.tiledMapRectArray[i][j] = new Phaser.Geom.Rectangle(nextPosX - this.map.tileWidth / 2, nextPosY - this.map.tileHeight / 2, this.map.tileWidth, this.map.tileHeight);

          //node = new cc.Sprite();
          //this.addChild(node, 200);
          //node.setTextureRect(cc.rect(0, 0, tileSize.width - 2, tileSize.height - 2));
          //node.setColor(cc.color(122, 122, 255));
          //node.setPosition(nextPosX, nextPosY);
          //node.setOpacity(120);

          nextPosX += this.map.tileWidth;
      }

      nextPosX = (winSize.width - this.map.widthInPixels) / 2 + this.map.tileHeight / 2;
      nextPosY += this.map.tileHeight;
    }
    console.log('tiledMapRectArray', this.tiledMapRectArray)
  }

  loadTiledMapRectArrayMap() {
    var i;
    let tileHeight = this.map.tileHeight
    let tileWidth = this.map.tileWidth
    for (i = 0; i < tileHeight; i++) {
        this.tiledMapRectArrayMap[i] = [];
        for (var j = 0; j < tileWidth; j++) {
            this.tiledMapRectArrayMap[i][j] = tiledMapRectMapEnemu.NONE;
        }
    }
  }

  loadRoadPointArray() {
    this.roadPointArray = [];
    var roadGroup = this.map.getObjectLayer("road");
    var roads = roadGroup?.objects;
    var diff = (this.cameras.main.width - this.map.widthInPixels) /2
    if (!roads) {
      return
    }
    for (var i = 0; i < roads.length; i++) {
      const road = roads[i] as any
      this.roadPointArray.push(new Phaser.Geom.Rectangle(road.x + diff, road.y));
    }
  }

  loadObstacle() {
    // 小的路障
    this.loadSmallObstacle()
    // 中等的路障
    this.loadLittleObstacle()

    this.loadBigObstacle()

    // 禁用区域
    this.loadInvalidRect()
  }

  loadSmallObstacle () {
    const smallGroup = this.map.getObjectLayer("small");
    if (!smallGroup) {
      return
    }
    const smalls = smallGroup.objects;
    if (!smalls) {
      return
    }
    let node = null;
    let info = null;
    for (var i = 0; i < smalls.length; i++) {
      const small = smalls[i] as any

      // TODO: 路障的 偏移 未能校准
      node = this.add.sprite(small.x + 148, small.y + 45, small.name)
      info = this.getInfoFromMapByPos(node.x, node.y);
      this.tiledMapRectArrayMap[info.row][info.cel] = tiledMapRectMapEnemu.SMALL;
    }
  }

  loadLittleObstacle() {
    var littleGroup = this.map.getObjectLayer("little");
    if (!littleGroup) {
      return
    }
    var objs = littleGroup.objects;
    var node = null;
    var info = null;
    for (var i = 0; i < objs.length; i++) {
      const obj = objs[i] as any
      node = this.add.sprite(obj.x + 113, obj.y + 45, obj.name)


      info = this.getInfoFromMapByPos(node.x, node.y);
      this.tiledMapRectArrayMap[info.row][info.cel] = tiledMapRectMapEnemu.LITTLE;
      this.tiledMapRectArrayMap[info.row][info.cel - 1] = tiledMapRectMapEnemu.LITTLE;
    }
  }

  loadBigObstacle() {
    var smallGroup = this.map.getObjectLayer("big");
    if (!smallGroup) {
      return
    }
    var smalls = smallGroup.objects;
    var node = null;
    var info = null;
    for (var i = 0; i < smalls.length; i++) {
      const small = smalls[i] as any
        node = this.add.sprite(small.x + 113, small.y + 80, small.name)
        info = this.getInfoFromMapByPos(node.x, node.y);
        this.tiledMapRectArrayMap[info.row][info.cel] = tiledMapRectMapEnemu.BIG;
        this.tiledMapRectArrayMap[info.row][info.cel- 1] = tiledMapRectMapEnemu.BIG;
        this.tiledMapRectArrayMap[info.row -1][info.cel] = tiledMapRectMapEnemu.BIG;
        this.tiledMapRectArrayMap[info.row- 1][info.cel - 1] = tiledMapRectMapEnemu.BIG;
    }
  }

  loadInvalidRect() {
    var invalidGroup = this.map.getObjectLayer("invalid");
    if (!invalidGroup) {
      return
    }
    var invalids = invalidGroup.objects;
    var data = null;
    var info = null;
    for (var i = 0; i < invalids.length; i++) {
      data = invalids[i] as any;
      // data.x += invalidGroup.getPositionOffset().x;
      // data.y += invalidGroup.getPositionOffset().y;

      info = this.getInfoFromMapByPos(data.x, data.y);
      if (info.isInMap) {
        this.tiledMapRectArrayMap[info.row][info.cel] = tiledMapRectMapEnemu.INVALID;
      }
    }
  }

  loadRoadMap() {
    var roadGroup = this.map.getObjectLayer("road");
    if (!roadGroup) {
      return
    }
    var roads = roadGroup.objects;
    var diff = (this.cameras.main.width - this.map.widthInPixels) / 2
    var currPoint = null;
    var nextPoint = null;
    var offsetCount = 0;
    var info = null;
    var j = 0;
    for (var i = 0; i < roads.length - 1; i++) {
      const road = roads[i] as any
      const nextRoad = roads[i + 1] as any
        currPoint = new Phaser.Geom.Rectangle(road.x + diff, road.y);
        nextPoint = new Phaser.Geom.Rectangle(nextRoad.x + diff, nextRoad.y);

        info = this.getInfoFromMapByPos(currPoint.x, currPoint.y);

        if (currPoint.y == nextPoint.y) {   // X 轴方向
            offsetCount = Math.abs(nextPoint.x - currPoint.x) / this.map.tileWidth + 1;
            // X 轴方向[向左]
            if (currPoint.x > nextPoint.x) {
                for (j = 0; j < offsetCount; j++) {
                    this.tiledMapRectArrayMap[info.row][info.cel - j] = tiledMapRectMapEnemu.ROAD;
                }
            }else{   // X 轴方向[向右]
                for (j = 0; j < offsetCount; j++) {
                    this.tiledMapRectArrayMap[info.row][info.cel + j] = tiledMapRectMapEnemu.ROAD;
                }
            }
        }else{   // Y 轴方向
            offsetCount = Math.abs(nextPoint.y - currPoint.y) / this.map.tileHeight + 1;
            // Y 轴方向[向下]
            if (currPoint.y > nextPoint.y){
                for (j = 0; j < offsetCount; j++) {
                    this.tiledMapRectArrayMap[info.row - j][info.cel ] = tiledMapRectMapEnemu.ROAD;
                }
            }else{   // Y 轴方向[向上]
                for (j = 0; j < offsetCount; j++) {
                    this.tiledMapRectArrayMap[info.row + j][info.cel ] = tiledMapRectMapEnemu.ROAD;
                }
            }
        }
    }
  }

  loadNextGroupMonster() {
    if (this.groupCount >= GameState.MAX_GROUP_COUNT) {
      console.log('最后一关了')
      return 
    }
    this.groupCount ++
    this.monsterCount = 0
    this.time.addEvent({ delay: 1000, callback: this.createMonster, callbackScope: this, repeat: GameState.GROUP_MONSTER_COUNT });
  }

  createMonster() {
    if (this.monsterCount >= GameState.GROUP_MONSTER_COUNT) {
      this.time.addEvent({ delay: 2000, callback: this.loadNextGroupMonster, callbackScope: this });
    }
    this.monsterCount ++
    var monsterData = {
      road : this.roadPointArray,
      speed : 0.1,
      index : 0
    };
    // var monster = new Monster(this, 264, 250, 'theme', 'Theme1/Monster/L11.png')
    var monster = new Monster(this, 264, 250, 'Monster_L11.png')
    // this.physics.add.existing(monster, false)
    monster.setPosition(this.roadPointArray[0].x, this.roadPointArray[0].y);

    monster.setCustomData(monsterData)
    monster.setKill((val: number) => {
      const newValue = Math.floor(this.healthValue - val)

      if (newValue > 0) {
        this.healthValue = newValue
        this.healthText.setText(this.healthValue + '')
        this.carrot.setTexture(`end_sign_pic${this.healthValue}`)
      } else {
        // TODO: 清理计时器
        console.log('game over')
        this.scene.stop()
        // TODO: 失败画面，失败的音乐。
        setTimeout(() => {
          this.scene.start('GameResult')
        }, 1000)
      }
    })
    monster.run()
    this.add.existing(monster);
    this.monsters.add(monster)
  }

  loadTouchWarning (x: number, y: number) {
    var warningSprite: Phaser.GameObjects.Sprite
    // if (this.touchWarningNode !== null) {
    //   warningSprite = this.touchWarningNode
    //   this.tweens.stop()
    // } else {
      warningSprite = this.add.sprite(x, y, 'warning')
    // }
    // 
    warningSprite.setAlpha(1)

    this.tweens.add({
      delay: 400,
      targets: warningSprite,
      alpha: {warningSprite: 0, duration: 300, ease: 'Expo.easeOut'},
      onComplete: () => {
        warningSprite.destroy()
      }
    })
  }

  loadTowerPanel (args: any) {
    var panel = new TowerPanel(this, 0, 0)

    panel.loadProperty(args)
    panel.setCallback(this.removeTower.bind(this))
    this.add.existing(panel)
    this.towerPanel = panel;
  }

  removeTower () {
    this.createTower(this.towerPanel.getData())
    setTimeout(() => {
      this.towerPanel && this.towerPanel.destroyAll()
      this.towerPanel = null
    }, 200)
  }

  createTower (data: any) {
    if (!data) {
      console.log('wandan,', this.towerPanel)
      return 
    }
    let name = data.bot.name
    if (!name) {
      console.log('请确定武器名称')
      return ;
    }

    var towerData = {} as any;
    towerData.name = name;
    towerData.x = data.x;
    towerData.y = data.y;
    console.log(data.x, data.y)
    var node = null;
    switch (name){
        case "bottle":
            towerData.scope = 300;
            towerData.bulletSpeed = 40;
            node = new TowerBase(this, data.x, data.y, towerData, this.monsters);

            node.setOverCallback(() => {
              this.loadNextGroupMonster()
            })
            break;
        default :
            console.log("GPMainLayer.createTower() : 异常");
            break;
    }

    // 属性设置
    if (node != null) {
        // 标记当前位置有塔
        this.tiledMapRectArrayMap[data.row][data.cel] = tiledMapRectMapEnemu.TOWER;
    }

    return node;
  }

  // 根据坐标获取在地图中的信息
  getInfoFromMapByPos (x: number, y: number){
    if (y === undefined) {
      console.log("GPMainLayer.getInfoFromMapByPos(): Y坐标不能为空！")
    }

    var isInMap = false;
    var index = {
      row: 0,
      cel: 0,
      x : -1,
      y : -1
    };
    var rect = null;
    for (var i = 0; i < this.tiledMapRectArray.length; i++) {
        for (var j = 0; j < this.tiledMapRectArray[i].length; j++) {
            rect = this.tiledMapRectArray[i][j];
            if (Phaser.Geom.Rectangle.ContainsPoint(rect, new Phaser.Geom.Point(x, y))) {
                index.row = i;
                index.cel = j;
                index.x = rect.x;
                index.y = rect.y;
                isInMap = true;
                // console.log("GPMainLayer.getInfoFromMapByPos() : rect is ", rect);
            }
        }
    }

    return {
        isInMap : isInMap,
        row : index.row,  // 行
        cel : index.cel,  // 列
        x : index.x,
        y : index.y
    };
  }
}